<template>
	<view class="content">
		<u-navbar bgColor="#F5F9FC" :placeholder="true" :border="true" height="48px">
			<view slot="left" class="navbar-left">
				<navigator class="back-button">
					<view class="nav-back-content">
						<view class="nav-title">记账</view>
					</view>
				</navigator>
			</view>
		</u-navbar>

		<view class="filter-container">
			<view class="filter-item" @click="showYearPicker = true">
				<u-icon name="calendar" size="16" color="#4188EF"></u-icon>
				<text>{{ selectedYear }}年</text>
				<u-icon name="arrow-down" size="14" color="#4188EF"></u-icon>
			</view>
			<view class="filter-item" @click="showQuarterPicker = true">
				<u-icon name="calendar" size="16" color="#4188EF"></u-icon>
				<text>第{{ selectedQuarter }}季度</text>
				<u-icon name="arrow-down" size="14" color="#4188EF"></u-icon>
			</view>
			<view class="filter-item" @click="showMonthPicker = true">
				<u-icon name="calendar" size="16" color="#4188EF"></u-icon>
				<text>{{ selectedMonth }}月</text>
				<u-icon name="arrow-down" size="14" color="#4188EF"></u-icon>
			</view>
		</view>

		<view class="account-container">
			<view class="account-box" v-for="(item,index) in filteredAccountList" :key="index">
				<view class="account-header">
					<view class="account-title">
						<view class="img-bg" :class="item.type">
							<image class="account-icon" :src="getAccountIcon(item.type)"></image>
						</view>
						<text class="account-name">{{item.title}}</text>
					</view>
					<view :class="item.status == 'completed' ? 'status-completed' : 'status-pending'">
						{{item.statusText}}
					</view>
				</view>

				<view class="account-details">
					<view class="account-info" v-for="(detail, detailIndex) in item.details" :key="detailIndex">
						<text class="label">{{detail.label}}：</text>
						<text class="value">{{detail.value}}</text>
					</view>
				</view>

				<view class="account-actions">
					<view class="action-btn preview-btn" @click="previewFile(item)"
						:class="item.status == 'pending' ? 'disabled' : ''">
						<u-icon name="eye" size="14" color="#4188EF"></u-icon>
						<text>预览</text>
					</view>
					<view class="action-btn process-btn" @click="handleProcess(item)"
						:class="item.status == 'completed' ? 'completed' : ''">
						<u-icon name="edit-pen" size="14" color="#4188EF"></u-icon>
						<text>{{ item.status == 'completed' ? '已处理' : '立即处理' }}</text>
					</view>
				</view>
			</view>
		</view>

		<u-popup :show="showProcessDialog" @close="showProcessDialog = false" round="10" mode="center">
			<view class="process-dialog">
				<view class="dialog-title">处理{{ currentItem.title }}</view>
				<view class="dialog-content">
					<text v-if="currentItem.type === 'salary'">人员是否有变化？</text>
					<text v-else-if="currentItem.type === 'receive-invoice'">发票是否已确认？</text>
					<text v-else-if="currentItem.type === 'issue-invoice'">发票是否已确认？</text>
					<text v-else-if="currentItem.type === 'bank'">银行流水是否已核对？</text>
				</view>
				<view class="dialog-actions">
					<view class="dialog-btn no-btn" @click="handleNoChange">无变化</view>
					<view class="dialog-btn yes-btn" @click="handleHasChange">有变化</view>
				</view>
			</view>
		</u-popup>

		<u-picker :show="showYearPicker" :columns="[yearColumns]" @confirm="confirmYear"
			@cancel="showYearPicker = false"></u-picker>

		<u-picker :show="showQuarterPicker" :columns="[quarterColumns]" @confirm="confirmQuarter"
			@cancel="showQuarterPicker = false"></u-picker>

		<u-picker :show="showMonthPicker" :columns="[monthColumns]" @confirm="confirmMonth"
			@cancel="showMonthPicker = false"></u-picker>
	</view>
</template>

<script>
	import {
		currentCompanyApi
	} from "@/api/auth.js"

	export default {
		data() {
			const currentYear = new Date().getFullYear()
			const currentMonth = new Date().getMonth() + 1
			const currentQuarter = Math.ceil(currentMonth / 3)

			return {
				// 公司相关信息
				http: uni.$u.http, // 统一请求实例
				isLogin: false,
				companyId: null,
				companyInfo: {},

				// 日期选择相关
				selectedYear: currentYear,
				selectedQuarter: currentQuarter,
				selectedMonth: currentMonth,
				showYearPicker: false,
				showQuarterPicker: false,
				showMonthPicker: false,
				showProcessDialog: false,
				currentItem: null,
				yearColumns: [],
				quarterColumns: [],
				monthColumns: [],
				currentFilter: 'month', // month, quarter, year

				// 记账数据
				accountData: {
					salary: {},
					receiveInvoice: {},
					issueInvoice: {},
					bank: {}
				}
			}
		},
		computed: {
			filteredAccountList() {
				if (this.currentFilter === 'year') {
					return this.getYearData(this.selectedYear)
				} else if (this.currentFilter === 'quarter') {
					return this.getQuarterData(this.selectedYear, this.selectedQuarter)
				} else {
					return this.getMonthData(this.selectedYear, this.selectedMonth)
				}
			}
		},
		onShow() {
			// 检查登录状态
			this.isLogin = uni.getStorageSync('isLogin')
			if (!this.isLogin) {
				uni.reLaunch({
					url: '/pages/login/login'
				})
				return
			}

			// 获取当前公司信息
			this.getCurrentCompany()
		},
		methods: {
			// 获取当前公司信息
			getCurrentCompany() {
				currentCompanyApi().then(res => {
					if (res.code == 200) {
						if (res.data) {
							this.companyInfo = res.data
							this.companyId = res.data.id
							uni.setStorageSync('companyInfo', res.data)

							// 初始化选择器数据
							this.initPickerData()

							// 获取记账数据
							this.getAccountingData()
						} else {
							// 未绑定公司，跳转到绑定页面
							uni.navigateTo({
								url: '/subpackageTwo/pages/addCompany/addCompany'
							})
						}
					}
				})
			},

			// 获取记账数据
			getAccountingData() {
				if (!this.companyId) return

				// 根据当前筛选条件请求对应的数据
				let url = '/accounting/records'
				let params = {
					companyId: this.companyId,
					filterType: this.currentFilter,
					year: this.selectedYear
				}

				if (this.currentFilter === 'quarter') {
					params.quarter = this.selectedQuarter
				} else if (this.currentFilter === 'month') {
					params.month = this.selectedMonth
				}

				// 使用统一的请求实例发送请求
				this.http.get(url, {
					params
				}).then(res => {
					if (res.code == 200 && res.data) {
						this.accountData = res.data
					}
				}).catch(err => {
					console.error('获取记账数据失败', err)
				})
			},

			// 获取图标路径
			getAccountIcon(type) {
				const icons = {
					'salary': '../../static/images/owner.png',
					'receive-invoice': '../../static/images/company.png',
					'issue-invoice': '../../static/images/up.png',
					'bank': '../../static/images/owner.png'
				}
				return icons[type] || '../../static/images/owner.png'
			},

			// 生成月度数据
			getMonthData(year, month) {
				// 判断是否为当前月或未来月份
				const now = new Date()
				const isCurrentMonth = year === now.getFullYear() && month === now.getMonth() + 1
				const isFutureMonth = year > now.getFullYear() || (year === now.getFullYear() && month > now.getMonth() +
					1)

				// 使用接口返回的实际数据，如果没有则使用默认数据
				const salaryData = this.accountData.salary.month || {
					budget: '85,600.00',
					actual: '78,200.00',
					tax: '7,400.00'
				}

				const receiveInvoiceData = this.accountData.receiveInvoice.month || {
					count: isCurrentMonth ? '0' : '15',
					total: isCurrentMonth ? '0.00' : '156,800.00',
					tax: isCurrentMonth ? '0.00' : '12,544.00'
				}

				const issueInvoiceData = this.accountData.issueInvoice.month || {
					count: '28',
					total: '234,500.00',
					tax: '18,760.00'
				}

				const bankData = this.accountData.bank.month || {
					income: '345,200.00',
					expenditure: '287,600.00',
					balance: '57,600.00'
				}

				return [{
						title: `${month}月份工资单`,
						type: 'salary',
						status: isCurrentMonth ? 'pending' : 'completed',
						statusText: isCurrentMonth ? '未录入' : '已完成',
						details: [{
								label: '预算',
								value: `¥${salaryData.budget}`
							},
							{
								label: '实发',
								value: `¥${salaryData.actual}`
							},
							{
								label: '个税',
								value: `¥${salaryData.tax}`
							}
						]
					},
					{
						title: `${month}月份收到的发票`,
						type: 'receive-invoice',
						status: isCurrentMonth ? 'completed' : 'completed',
						statusText: isCurrentMonth ? '无发票' : '已完成',
						details: [{
								label: '发票数量',
								value: `${receiveInvoiceData.count}张`
							},
							{
								label: '发票总额',
								value: `¥${receiveInvoiceData.total}`
							},
							{
								label: '税额',
								value: `¥${receiveInvoiceData.tax}`
							}
						]
					},
					{
						title: `${month}月份开出的发票`,
						type: 'issue-invoice',
						status: 'completed',
						statusText: '已完成',
						details: [{
								label: '发票数量',
								value: `${issueInvoiceData.count}张`
							},
							{
								label: '发票总额',
								value: `¥${issueInvoiceData.total}`
							},
							{
								label: '税额',
								value: `¥${issueInvoiceData.tax}`
							}
						]
					},
					{
						title: `${month}月份银行明细回单`,
						type: 'bank',
						status: 'completed',
						statusText: '已完成',
						details: [{
								label: '收入总额',
								value: `¥${bankData.income}`
							},
							{
								label: '支出总额',
								value: `¥${bankData.expenditure}`
							},
							{
								label: '余额',
								value: `¥${bankData.balance}`
							}
						]
					}
				]
			},

			// 生成季度数据
			getQuarterData(year, quarter) {
				// 判断是否为当前季度或未来季度
				const now = new Date()
				const currentQuarter = Math.ceil((now.getMonth() + 1) / 3)
				const isCurrentQuarter = year === now.getFullYear() && quarter === currentQuarter
				const isFutureQuarter = year > now.getFullYear() || (year === now.getFullYear() && quarter >
					currentQuarter)

				// 使用接口返回的实际数据，如果没有则使用默认数据
				const salaryData = this.accountData.salary.quarter || {
					budget: '256,800.00',
					actual: '234,600.00',
					tax: '22,200.00'
				}

				const receiveInvoiceData = this.accountData.receiveInvoice.quarter || {
					count: isCurrentQuarter ? '0' : '45',
					total: isCurrentQuarter ? '0.00' : '468,000.00',
					tax: isCurrentQuarter ? '0.00' : '37,440.00'
				}

				const issueInvoiceData = this.accountData.issueInvoice.quarter || {
					count: '84',
					total: '703,500.00',
					tax: '56,280.00'
				}

				const bankData = this.accountData.bank.quarter || {
					income: '1,035,600.00',
					expenditure: '862,800.00',
					balance: '172,800.00'
				}

				return [{
						title: `${year}年第${quarter}季度工资单`,
						type: 'salary',
						status: isCurrentQuarter ? 'pending' : 'completed',
						statusText: isCurrentQuarter ? '未录入' : '已完成',
						details: [{
								label: '季度预算',
								value: `¥${salaryData.budget}`
							},
							{
								label: '季度实发',
								value: `¥${salaryData.actual}`
							},
							{
								label: '季度个税',
								value: `¥${salaryData.tax}`
							}
						]
					},
					{
						title: `${year}年第${quarter}季度收到的发票`,
						type: 'receive-invoice',
						status: isCurrentQuarter ? 'completed' : 'completed',
						statusText: isCurrentQuarter ? '无发票' : '已完成',
						details: [{
								label: '季度发票数量',
								value: `${receiveInvoiceData.count}张`
							},
							{
								label: '季度发票总额',
								value: `¥${receiveInvoiceData.total}`
							},
							{
								label: '季度税额',
								value: `¥${receiveInvoiceData.tax}`
							}
						]
					},
					{
						title: `${year}年第${quarter}季度开出的发票`,
						type: 'issue-invoice',
						status: 'completed',
						statusText: '已完成',
						details: [{
								label: '季度发票数量',
								value: `${issueInvoiceData.count}张`
							},
							{
								label: '季度发票总额',
								value: `¥${issueInvoiceData.total}`
							},
							{
								label: '季度税额',
								value: `¥${issueInvoiceData.tax}`
							}
						]
					},
					{
						title: `${year}年第${quarter}季度银行明细回单`,
						type: 'bank',
						status: 'completed',
						statusText: '已完成',
						details: [{
								label: '季度收入总额',
								value: `¥${bankData.income}`
							},
							{
								label: '季度支出总额',
								value: `¥${bankData.expenditure}`
							},
							{
								label: '季度余额',
								value: `¥${bankData.balance}`
							}
						]
					}
				]
			},

			// 生成年度数据
			getYearData(year) {
				// 判断是否为当前年度或未来年度
				const now = new Date()
				const isCurrentYear = year === now.getFullYear()
				const isFutureYear = year > now.getFullYear()

				// 使用接口返回的实际数据，如果没有则使用默认数据
				const salaryData = this.accountData.salary.year || {
					budget: '1,027,200.00',
					actual: '938,400.00',
					tax: '88,800.00'
				}

				const receiveInvoiceData = this.accountData.receiveInvoice.year || {
					count: isCurrentYear ? '0' : '256',
					total: isCurrentYear ? '0.00' : '2,580,000.00',
					tax: isCurrentYear ? '0.00' : '206,400.00'
				}

				const issueInvoiceData = this.accountData.issueInvoice.year || {
					count: '336',
					total: '2,814,000.00',
					tax: '225,120.00'
				}

				const bankData = this.accountData.bank.year || {
					income: '4,142,400.00',
					expenditure: '3,451,200.00',
					balance: '691,200.00'
				}

				return [{
						title: `${year}年工资单`,
						type: 'salary',
						status: isCurrentYear ? 'pending' : 'completed',
						statusText: isCurrentYear ? '未录入' : '已完成',
						details: [{
								label: '年度预算',
								value: `¥${salaryData.budget}`
							},
							{
								label: '年度实发',
								value: `¥${salaryData.actual}`
							},
							{
								label: '年度个税',
								value: `¥${salaryData.tax}`
							}
						]
					},
					{
						title: `${year}年收到的发票`,
						type: 'receive-invoice',
						status: isCurrentYear ? 'completed' : 'completed',
						statusText: isCurrentYear ? '无发票' : '已完成',
						details: [{
								label: '年度发票数量',
								value: `${receiveInvoiceData.count}张`
							},
							{
								label: '年度发票总额',
								value: `¥${receiveInvoiceData.total}`
							},
							{
								label: '年度税额',
								value: `¥${receiveInvoiceData.tax}`
							}
						]
					},
					{
						title: `${year}年开出的发票`,
						type: 'issue-invoice',
						status: 'completed',
						statusText: '已完成',
						details: [{
								label: '年度发票数量',
								value: `${issueInvoiceData.count}张`
							},
							{
								label: '年度发票总额',
								value: `¥${issueInvoiceData.total}`
							},
							{
								label: '年度税额',
								value: `¥${issueInvoiceData.tax}`
							}
						]
					},
					{
						title: `${year}年银行明细回单`,
						type: 'bank',
						status: 'completed',
						statusText: '已完成',
						details: [{
								label: '年度收入总额',
								value: `¥${bankData.income}`
							},
							{
								label: '年度支出总额',
								value: `¥${bankData.expenditure}`
							},
							{
								label: '年度余额',
								value: `¥${bankData.balance}`
							}
						]
					}
				]
			},

			initPickerData() {
				const currentYear = new Date().getFullYear()
				this.yearColumns = []
				for (let year = currentYear; year >= 1949; year--) {
					this.yearColumns.push(year + '年')
				}

				this.quarterColumns = ['第一季度', '第二季度', '第三季度', '第四季度']

				this.monthColumns = []
				for (let month = 1; month <= 12; month++) {
					this.monthColumns.push(month + '月')
				}
			},

			confirmYear(e) {
				const yearStr = e.value[0]
				const year = parseInt(yearStr)
				this.selectedYear = year
				this.showYearPicker = false
				this.currentFilter = 'year'
				this.selectedQuarter = 1
				this.selectedMonth = 1

				// 获取对应年份的数据
				this.getAccountingData()
			},

			confirmQuarter(e) {
				const quarterStr = e.value[0]
				const quarterMap = {
					'第一季度': 1,
					'第二季度': 2,
					'第三季度': 3,
					'第四季度': 4
				}
				this.selectedQuarter = quarterMap[quarterStr] || 1
				this.showQuarterPicker = false
				this.currentFilter = 'quarter'

				// 获取对应季度的数据
				this.getAccountingData()
			},

			confirmMonth(e) {
				const monthStr = e.value[0]
				const month = parseInt(monthStr)
				this.selectedMonth = month
				this.showMonthPicker = false
				this.currentFilter = 'month'
				this.selectedQuarter = Math.ceil(month / 3)

				// 获取对应月份的数据
				this.getAccountingData()
			},

			handleProcess(item) {
				if (item.status === 'completed') {
					return
				}
				this.currentItem = item
				this.showProcessDialog = true
			},

			handleNoChange() {
				this.showProcessDialog = false
				this.processItem('无变化')
			},

			handleHasChange() {
				this.showProcessDialog = false
				this.processItem('有变化')
			},

			processItem(result) {
				// 调用处理接口
				if (!this.companyId || !this.currentItem) return

				const url = '/accounting/process'
				const data = {
					companyId: this.companyId,
					type: this.currentItem.type,
					year: this.selectedYear,
					result: result
				}

				if (this.currentFilter === 'quarter') {
					data.quarter = this.selectedQuarter
				} else if (this.currentFilter === 'month') {
					data.month = this.selectedMonth
				}

				this.http.post(url, data).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '处理成功',
							icon: 'success'
						})
						// 重新获取数据
						this.getAccountingData()
					}
				}).catch(err => {
					console.error('处理记账项目失败', err)
					uni.showToast({
						title: '处理失败',
						icon: 'none'
					})
				})
			},

			previewFile(item) {
				if (item.status !== 'completed') {
					uni.showToast({
						title: '暂无文件可预览',
						icon: 'none'
					})
					return
				}

				// 调用预览接口
				if (!this.companyId) return

				const url = '/accounting/preview'
				const params = {
					companyId: this.companyId,
					type: item.type,
					year: this.selectedYear
				}

				if (this.currentFilter === 'quarter') {
					params.quarter = this.selectedQuarter
				} else if (this.currentFilter === 'month') {
					params.month = this.selectedMonth
				}

				this.http.get(url, {
					params
				}).then(res => {
					if (res.code == 200 && res.data && res.data.url) {
						// 打开预览文件
						uni.navigateTo({
							url: `/pages/preview/index?url=${encodeURIComponent(res.data.url)}`
						})
					} else {
						uni.showToast({
							title: '预览文件不存在',
							icon: 'none'
						})
					}
				}).catch(err => {
					console.error('获取预览文件失败', err)
					uni.showToast({
						title: '预览功能开发中',
						icon: 'none'
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		background: #f8f9fa;
		min-height: 100vh;
		padding-bottom: 40rpx;

		.navbar-left {
			.nav-back-content {
				display: flex;
				align-items: center;

				.nav-title {
					font-size: 34rpx;
					font-weight: bold;
					color: #1e88e5;
					margin-left: 16rpx;
				}
			}
		}

		.filter-container {
			padding: 30rpx 32rpx;
			display: flex;
			justify-content: space-between;
			background: #fff;
			border-bottom: 1rpx solid #e0e0e0;

			.filter-item {
				display: flex;
				align-items: center;
				padding: 20rpx 30rpx;
				background: #f8f9fa;
				border-radius: 12rpx;
				font-size: 28rpx;
				color: #333;
				border: 2rpx solid #e0e0e0;

				u-icon:first-child {
					margin-right: 10rpx;
				}

				u-icon:last-child {
					margin-left: 10rpx;
				}
			}
		}

		.account-container {
			padding: 30rpx 32rpx;

			.account-box {
				background: #fff;
				border-radius: 16rpx;
				padding: 32rpx;
				margin-bottom: 24rpx;
				box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

				.account-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 25rpx;

					.account-title {
						display: flex;
						align-items: center;

						.img-bg {
							width: 70rpx;
							height: 70rpx;
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							margin-right: 20rpx;
							background: #e6f3ff;

							.account-icon {
								width: 70rpx;
								height: 70rpx;
								border-radius: 50%;
							}

							&.salary {
								background: #e6f3ff;
							}

							&.receive-invoice {
								background: #fff2e8;
							}

							&.issue-invoice {
								background: #f6ffed;
							}

							&.bank {
								background: #f0f5ff;
							}
						}

						.account-name {
							font-size: 32rpx;
							font-weight: bold;
							color: #333;
						}
					}

					.status-completed,
					.status-pending {
						padding: 8rpx 20rpx;
						border-radius: 20rpx;
						font-size: 24rpx;
						font-weight: bold;
					}

					.status-completed {
						background: #f6ffed;
						color: #52c41a;
						border: 1rpx solid #b7eb8f;
					}

					.status-pending {
						background: #fff7e6;
						color: #fa8c16;
						border: 1rpx solid #ffd591;
					}
				}

				.account-details {
					margin-bottom: 30rpx;

					.account-info {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 12rpx 0;
						border-bottom: 1rpx solid #f0f0f0;

						&:last-child {
							border-bottom: none;
						}

						.label {
							font-size: 28rpx;
							color: #666;
						}

						.value {
							font-size: 28rpx;
							color: #333;
							font-weight: bold;
						}
					}
				}

				.account-actions {
					display: flex;
					justify-content: flex-end;
					gap: 20rpx;

					.action-btn {
						display: flex;
						align-items: center;
						justify-content: center;
						padding: 16rpx 32rpx;
						border-radius: 16rpx;
						font-size: 24rpx;
						font-weight: bold;
						min-width: 140rpx;
						color: #4188EF;
						background: #deebff;
						box-shadow: 0rpx 2rpx 4rpx 2rpx rgba(0, 0, 0, 0.06);

						u-icon {
							margin-right: 8rpx;
						}

						&.preview-btn.disabled {
							opacity: 0.6;
						}

						&.process-btn.completed {
							background: #f6ffed;
							color: #52c41a;
						}
					}
				}
			}
		}

		.process-dialog {
			width: 600rpx;
			padding: 40rpx;
			background: #fff;
			border-radius: 20rpx;

			.dialog-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				text-align: center;
				margin-bottom: 30rpx;
			}

			.dialog-content {
				font-size: 28rpx;
				color: #666;
				text-align: center;
				margin-bottom: 40rpx;
				padding: 0 20rpx;
			}

			.dialog-actions {
				display: flex;
				justify-content: space-between;
				gap: 20rpx;

				.dialog-btn {
					flex: 1;
					padding: 20rpx;
					border-radius: 16rpx;
					font-size: 24rpx;
					font-weight: bold;
					text-align: center;
					color: #4188EF;
					background: #deebff;
					box-shadow: 0rpx 2rpx 4rpx 2rpx rgba(0, 0, 0, 0.06);
				}
			}
		}
	}
</style>